package org.tomac.io.fix;

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.URI;

import org.tomac.io.IIOPlexor;

public class FixURL implements IFixURL {
	byte[] targetCompID;
	byte[] senderCompID;
	int heartBeatIntInSec;
	String host;
	int port;
	SocketAddress socketAddress;
	protected boolean isAcceptor;
	String url;
	

	/**
	 * FixURL URI formated as <protocol><version>://<senderCompID>:<targetCompID>@<host>:<port>/[?[<heartBeatInt=nn>]&[<...>]#[acceptor|initiator]
	 * Example: fix42nordic://ISLD:TW@127.0.0.1:1212/ISLD/TW?heartBtInt=60#acceptor
	 * @param string
	 */
	public FixURL(String url) {
		this.url = url;
		URI uri = URI.create(url);

		host = uri.getHost();
		port = uri.getPort();
		socketAddress = new InetSocketAddress(host, port);

		isAcceptor = uri.getFragment().toUpperCase().startsWith("acceptor".toUpperCase());

		senderCompID = uri.getUserInfo().split(":")[0].trim().getBytes();
		targetCompID = uri.getUserInfo().split(":")[1].trim().getBytes();
		
		if ( uri.getQuery() != null ) {
			String[] querySplit = uri.getQuery().split("&");
			if (querySplit.length > 0 ) { 
				String[] queryValueSplit = querySplit[0].split("=");
				if (queryValueSplit.length > 0) heartBeatIntInSec = Integer.valueOf(queryValueSplit[1].trim());
			}
			else heartBeatIntInSec = Integer.valueOf(System.getProperty("fix.heartbtint", "60"));
		}

	}

	@Override
	public SocketAddress getIpAddress() {
		return socketAddress;
	}

	@Override
	public long getHeartBtInt() {
		return heartBeatIntInSec * 1000;
	}

	@Override
	public byte[] getTargetCompID() {
		return targetCompID;
	}

	@Override
	public byte[] getSenderCompID() {
		return senderCompID;
	}
	
	@Override
	public String toString() {
		return new String(url);
	}

	@Override
	public URI getInboundFixLog() {
		String type = "initiator";
		if (isAcceptor) type = "acceptor";
		String c = (System.getProperty("file.separator")).equals("\\") ? "/" : "";
		return URI.create(System.getProperty("fix.inboundlog", "file://" + c + System.getProperty("user.dir").replace(System.getProperty("file.separator"), "/") + "/" + "fixin-" + type));
	}

	@Override
	public URI getOutboundFixLog() {
		String type = "initiator";
		if (isAcceptor) type = "acceptor";
		String c = (System.getProperty("file.separator")).equals("\\") ? "/" : "";
		return URI.create(System.getProperty("fix.outboundlog", "file://" + c + System.getProperty("user.dir").replace(System.getProperty("file.separator"), "/") + "/" + "fixout-" + type));
	}

}
